<template>
  <el-card class="main-card">
    <div class="title">{{this.$route.meta.menuName }}</div>
    <!-- 表格操作 -->
    <div class="operation-container">
      <el-button
          type=""
          size="small"
          @click="editArticle(null)"
      >
        新增
      </el-button>
      <el-button
          v-if="isDelete == 0"
          type="danger"
          size="small"
          icon="el-icon-delete"
          :disabled="articleIdList.length == 0"
          @click="updateIsDelete = true"
      >
        批量删除
      </el-button>
      <el-button
          v-else
          type="danger"
          size="small"
          icon="el-icon-delete"
          :disabled="articleIdList.length == 0"
          @click="remove = true"
      >
        批量删除
      </el-button>
      <!-- 条件筛选 -->
      <div style="margin-left:auto;margin-top: 3px;display: flex " >
        <!-- 分类 -->
        <el-select
            clearable
            size="small"
            v-model="typeId"
            filterable
            placeholder="请选择分类"
            style="margin-right:1rem"
        >
          <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
        <!-- 标签 -->
<!--        &lt;!&ndash; 标签选项 &ndash;&gt;-->
<!--        <el-popover-->
<!--            placement="bottom-start"-->
<!--            width="210"-->
<!--            trigger="click"-->
<!--            style="margin-right:1rem"-->
<!--        >-->
<!--          &lt;!&ndash; 标签 &ndash;&gt;-->
<!--          <div class="popover-container">-->
<!--            <el-select v-model="tagId" collapse-tags multiple placeholder="请选择标签"  style="width: 200px">-->
<!--              <el-option-->
<!--                  v-for="item in tagList"-->
<!--                  :key="item.id"-->
<!--                  :label="item.name"-->
<!--                  :value="item.id"-->
<!--                  @change="handleIsopenSelect">-->
<!--              </el-option>-->
<!--            </el-select>-->
<!--          </div>-->
<!--          <el-button type="primary" plain slot="reference" size="small">-->
<!--            添加标签-->
<!--          </el-button>-->
<!--        </el-popover>-->
        <!-- 食物名 -->
        <el-input
            clearable
            v-model="keywords"
            prefix-icon="el-icon-search"
            size="small"
            placeholder="请输入食物名"
            style="width:200px"
            @keyup.enter.native="searchArticles"
        />
        <el-button
            type="primary"
            size="small"
            icon="el-icon-search"
            style="margin-left:1rem"
            @click="searchArticles"
        >
          搜索
        </el-button>
      </div>
    </div>
    <!-- 表格展示 -->
    <el-table
        border
        :data="articleList"
        @selection-change="selectionChange"
        v-loading="loading"
    >
      <!-- 表格列 -->
      <el-table-column type="selection" width="55" />
      <!-- 食物封面 -->
      <el-table-column
          prop="firstPicture"
          label="食物封面"
          width="180"
          align="center"
      >
        <template slot-scope="scope">
          <el-image
              class="article-cover"
              :src="
              getUrl(scope.row.pricutre)"
          />
          <i
              v-if="scope.row.status == 1"
              class="iconfont el-icon-mygongkai article-status-icon"
          />
          <i
              v-if="scope.row.status == 2"
              class="iconfont el-icon-mymima article-status-icon"
          />
          <i
              v-if="scope.row.status == 3"
              class="iconfont el-icon-mycaogaoxiang article-status-icon"
          />
        </template>
      </el-table-column>
      <!-- 食物标题 -->
      <el-table-column prop="name" label="食物名" align="center" />
      <!-- 食物分类 -->
      <el-table-column
          prop="type"
          label="分类"
          width="110"
          align="center">
        <template slot-scope="scope">
          <el-tag>
            {{scope.row.typeName}}
          </el-tag>
        </template>
      </el-table-column>
      <!-- 食物价格 -->
      <el-table-column
          prop="price"
          label="单价"
          width="70"
          align="center"
      >
      </el-table-column>
      <el-table-column prop="status" label="禁用" align="center" width="100">
        <template slot-scope="scope">
          <el-switch
              v-model="scope.row.status"
              active-color="#13ce66"
              inactive-color="#F4F4F5"
              :active-value=1
              :inactive-value=0
              @change="changeDisable(scope.row)"
          />
        </template>
      </el-table-column>
      <!-- 食物发表时间 -->
      <el-table-column
          prop="createTime"
          label="发表时间"
          width="130"
          align="center"
      >
        <template slot-scope="scope">
          <i class="el-icon-time" style="margin-right:5px" />
          {{
            parseAt(scope.row.createTime, "{y}-{m}-{d}-{h}")
          }}
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="操作" align="center" width="150">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="openDrawer(scope.row)">
            <i class="el-icon-edit" /> 标签
          </el-button>
          <el-button
              type="text"
              size="mini"
              @click="editArticle(scope.row.id)"
          >
            编辑
          </el-button>
          <el-popconfirm
              style="margin-left:10px"
              title="确定彻底删除吗？"
              @confirm="deleteArticles(scope.row.id)"
          >
            <el-button size="mini" type="text" slot="reference">
              删除
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
        class="pagination-container"
        background
        @size-change="sizeChange"
        @current-change="currentChange"
        :current-page="current"
        :page-size="size"
        :total="count"
        :page-sizes="[10, 20]"
        layout="total, sizes, prev, pager, next, jumper"
    />
    <!-- 批量逻辑删除对话框 -->
    <el-dialog :visible.sync="updateIsDelete" width="30%">
      <div class="dialog-title-container" slot="title">
        <i class="el-icon-warning" style="color:#ff9900" />提示
      </div>
      <div style="font-size:1rem">是否删除选中项？</div>
      <div slot="footer">
        <el-button @click="updateIsDelete = false">取 消</el-button>
        <el-button type="primary" @click="deleteArticles(null)">
          确 定
        </el-button>
      </div>
    </el-dialog>
    <!-- 批量彻底删除对话框 -->
    <el-dialog :visible.sync="remove" width="30%">
      <div class="dialog-title-container" slot="title">
        <i class="el-icon-warning" style="color:#ff9900" />提示
      </div>
      <div style="font-size:1rem">是否彻底删除选中项？</div>
      <div slot="footer">
        <el-button @click="remove = false">取 消</el-button>
        <el-button type="primary" @click="deleteArticles(null)">
          确 定
        </el-button>
      </div>
    </el-dialog>
<!--    id： 食物的id ; 子组件回调listArticles方法-->
    <food-edit-dialog :id="this.food_id" @listArticles="listArticles"/>

<!--右边弹出框-->
    <el-drawer
        :title="drawerName"
        :visible.sync="drawer"
        :direction="direction"
        :before-close="handleClose">
        <el-tree
            @check-change="handleCheckChange"
             :data="menuList"
            :default-checked-keys="menuIdList"
            :props="defaultProps"
            show-checkbox
            check-strictly
            node-key="id"
            ref="menuTree">
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>{{ node.label }}</span>
            <span v-if="data.children!=null">
               <el-select v-model="data.is_default" placeholder="默认选中" size="mini">
                <el-option
                    v-for="item in data.children"
                    :disabled="!item.check"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id">
                </el-option>
              </el-select>
               <el-button
                   type="text"
                   size="mini"
                   @click="openDesc(data)">
                设置描述
              </el-button>
            </span>
      </span>
        </el-tree>

    </el-drawer>
<!--标签描述对话框-->
    <el-dialog
        title="标签描述"
        :visible.sync="dialogVisibleDesc"
        width="30%">
      <span>
          <el-input v-model="TagDesc" type="textarea" placeholder="请输入描述"
                    :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
      </span>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisibleDesc = false">取 消</el-button>
    <el-button type="primary" @click="savaDesc">确 定</el-button>
  </span>
    </el-dialog>
  </el-card>
</template>

<script>

import {getFoodPage} from "@/api/food";
import FoodEditDialog from "@/components/foodEditDialog";
import {mapState} from "vuex";
import {Message} from "element-ui";
import {isExternal} from "@/utils/validate";

const {parseTime} = require("@/utils/data")
const {getTypeList, deleteFoodById,getTagMenuTree, savaTagTree, foodDisable} = require("@/api/food");
export default {
  components: {FoodEditDialog},
  created() {
    this.listArticles();
    this.listCategories();
    // this.listTags();
  },
  data: function() {
    return {
      TagDesc:"",
      TagDescId:null,
      dialogVisibleDesc:false,
      menuList:[],
      menuIdList:[],
      drawerName:"",
      drawer: false,
      direction: 'rtl',
      food_id:null,
      formData:{},
      loading: true,
      updateIsDelete: false,
      remove: false,
      activeStatus: "all",
      articleList: [],
      articleIdList: [],
      typeList: [],
      tagList: [],
      keywords: null,
      copyright: null,
      typeId: null,
      tagId: [],
      isDelete: 0,
      status: null,
      current: 1,
      size: 10,
      count: 0,
      ...mapState({
        foodEditDialog: state=>state.food.foodEditDialog,
      }),
      defaultProps: {
        children: 'children',
        label: 'label'
      }
    };
  },
  methods: {
    getUrl(url){
      if(url==null)
        return ""
      if(isExternal(url))
        return url;
      return "/api"+url;
    },
    parseAt(data ,str){
      return  parseTime(data,str)
    },
    handleCheckChange(data, checked, indeterminate) {
      //改变选中状态
      data.check=checked;
      console.log(data, checked, indeterminate);
    },
    savaDesc(){
      const index =this.getDescIndex();
      this.menuList[index].desc=this.TagDesc;
      this.dialogVisibleDesc=false;
    },
    openDesc(data){
      //保存此刻的标签id
      this.TagDescId = data.id
      const index =this.getDescIndex();
      console.log(index);
      this.TagDesc=this.menuList[index].desc;

      this.dialogVisibleDesc=true;
    },
    openDrawer(row){
      //通过食物id
      this.food_id=row.id;
      getTagMenuTree(row.id).then(res=>{
        console.log(res.data)
         this.menuIdList=[];

         res.data.forEach(item=>{
           if(item.check===true){
             this.menuIdList.push(item.id);
           }
           if(item.children!=null){
             item.children.forEach(item2=>{
               if(item2.check===true){
                 console.log(item2)
                 this.menuIdList.push(item2.id);
               }

               if(item2.is_default==1)
                 item.is_default=item2.id
             })
           }
         })

        this.menuList=res.data;
         console.log(this.menuIdList)
        this.drawerName=row.name;
        this.drawer=true;
        console.log("__"+this.drawer)
      })

    },
    handleClose(done) {
      this.$confirm('确认保存？')
          .then(_ => {
            //保存修改
            this.menuList.forEach(item=>{
              if(item.children!=null){
                item.children.forEach(item2=>{
                  //如果选中的是item2
                  if(item.is_default==item2.id){
                    item2.is_default=1;
                  }else {
                    item2.is_default=0;
                  }
                })
              }
              item.is_default=0;
            })
            const param = {
              "foodId" : this.food_id,
              "tagTree": this.menuList
            }
            console.log(param)
            savaTagTree(param).then(res=>{
              Message.success(res.msg);
              done();
            })

          })
          .catch(_ => {done();});
    },
    async changeDisable(row) {
      const params={
        id: row.id,
        isDisable: row.status
      }
      const res = await foodDisable(params);
      this.$notify.success({
        title: "成功",
        message: res.msg
      })
      await this.listArticles();
    },
    handleIsopenSelect(){
      this.$forceUpdate()
    },
    selectionChange(articleList) {
      this.articleIdList = [];
      articleList.forEach(item => {
        this.articleIdList.push(item.id);
      });
    },
    searchArticles() {
      this.current = 1;
      this.listArticles();
    },
    editArticle(id) {
      console.log(id)
      this.food_id=id
      this.$store.commit("food/OpenEditDialog")
    },

    async deleteArticles(id) {
      this.updateIsDelete = false;
      let param = []
      if (id == null) {
        param = this.articleIdList;
      } else {
        param = [id];
      }
      const res = await deleteFoodById(param);
      if (res.code) {
        this.$notify.success({
          title: "成功",
          message: res.msg
        });
        await this.listArticles();
      } else {
        this.$notify.error({
          title: "失败",
          message: res.msg
        });
      }
      this.remove = false;
    },
    sizeChange(size) {
      this.size = size;
      this.listArticles();
    },
    currentChange(current) {
      this.current = current;
      this.listArticles();
    },
    async listArticles() {
      const params = {
        currentPage: this.current,
        pageSize: this.size,
        queryString: this.keywords,
        typeId: this.typeId,
        tagId: this.tagId,
      }
      const res = await getFoodPage(params)
      console.log(res)
      this.articleList = res.data.records;
      this.count = res.data.total;
      this.loading = false;
    },
    async listCategories() {
      const res = await getTypeList();
      this.typeList = res.data;
    },
    async listTags() {
      const res = await getTagMenuTree();
      console.log(res.data)
      this.menuList = res.data;
      // this.tagList = res.data;
    },
    getDescIndex(){
      let index = this.menuList.findIndex(item=>item.id==this.TagDescId)
      return index;
    },
  },
  watch: {
    typeId() {
      this.current = 1;
      this.listArticles();
    },
    tagId() {
      this.current = 1;
      this.listArticles();
    },
    status() {
      this.current = 1;
      this.listArticles();
    },
    isDelete() {
      this.current = 1;
      this.listArticles();
    },


  },
  computed: {


    isActive() {
      return function(status) {
        return this.activeStatus == status ? "active-status" : "status";
      };
    }
  }
};
</script>

<style scoped>
.operation-container {
  margin-top: 1.5rem;
}
.article-status-menu {
  font-size: 14px;
  margin-top: 40px;
  color: #999;
}
.article-status-menu span {
  margin-right: 24px;
}
.status {
  cursor: pointer;
}
.active-status {
  cursor: pointer;
  color: #333;
  font-weight: bold;
}
.article-cover {
  position: relative;
  width: 100%;
  height: 90px;
  border-radius: 4px;
}
.article-cover::after {
  content: "";
  background: rgba(0, 0, 0, 0.3);
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}
.article-status-icon {
  color: #fff;
  font-size: 1.5rem;
  position: absolute;
  right: 1rem;
  bottom: 1.4rem;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
